package cn.micai.core.controller.admin;

import cn.micai.common.controller.BaseController;
import cn.micai.common.encode.MD5Pwd;
import cn.micai.common.page.Pagination;
import cn.micai.core.bean.product.*;
import cn.micai.core.bean.user.Admin;
import cn.micai.core.query.product.BrandQuery;
import cn.micai.core.query.product.ColorQuery;
import cn.micai.core.query.product.FeatureQuery;
import cn.micai.core.query.product.TypeQuery;
import cn.micai.core.query.user.AdminQuery;
import cn.micai.core.service.user.AdminService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;
import java.util.List;

/**
 * 管理员
 *
 * @author zhaoxinguo on 2017/8/4.
 */
@Controller
@RequestMapping(value = "/control")
public class AdminController extends BaseController{

    @Autowired
    private AdminService adminService; // 管理员

    //列表
    @RequestMapping(value = "/admin/list.do")
    public String list(Integer pageNo,String name,ModelMap model){
        //分页的参数
        StringBuilder params = new StringBuilder();

        //管理员条件对象
        AdminQuery adminQuery = new AdminQuery();

        //1.判断条件是否为Null
        if(StringUtils.isNotBlank(name)){
            adminQuery.setUsername(name);
            // 要求模糊查询
//            adminQuery.setUsernameLike(name);
            params.append("name=").append(name);
            //回显查询条件
            model.addAttribute("name", name);
        }

        //设置页号
        adminQuery.setPageNo(Pagination.cpn(pageNo));
        //设置每页数
        adminQuery.setPageSize(5);
        //按照ID倒排
        adminQuery.orderbyUsername(false);

        //4.加载带有分页的商品
        Pagination pagination = adminService.getAdminListWithPage(adminQuery);
        //分页页面展示
        pagination.pageView("/control/admin/list.do", params.toString());
        model.addAttribute("pagination", pagination);

        return "admin/list";
    }

    //去添加页面
    @RequestMapping(value = "/admin/toAdd.do")
    public String toAdd(ModelMap model){
        return "admin/add";
    }

    //管理员添加
    @RequestMapping(value = "/admin/add.do")
    public String add(Admin admin){
        //传管理员对象到Service
        admin.setPassword(mD5Pwd.encode(admin.getPassword()));
        admin.setRegisterTime(new Date());
        adminService.addAdmin(admin);
        return "redirect:/control/admin/list.do";
    }

}
